package com.bw.publish.ui

import android.R
import android.os.Environment
import android.view.View
import com.bw.common.utils.LogUtils
import com.bw.mvicore.ui.BaseActivity
import com.bw.publish.common.ConstantValue
import com.bw.publish.databinding.ActivityPublishBinding
import com.qiniu.pili.droid.shortvideo.PLAudioEncodeSetting
import com.qiniu.pili.droid.shortvideo.PLCameraSetting
import com.qiniu.pili.droid.shortvideo.PLFaceBeautySetting
import com.qiniu.pili.droid.shortvideo.PLMicrophoneSetting
import com.qiniu.pili.droid.shortvideo.PLRecordSetting
import com.qiniu.pili.droid.shortvideo.PLRecordStateListener
import com.qiniu.pili.droid.shortvideo.PLShortVideoEditor
import com.qiniu.pili.droid.shortvideo.PLShortVideoRecorder
import com.qiniu.pili.droid.shortvideo.PLVideoEditSetting
import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener
import com.qiniu.pili.droid.shortvideo.PLWatermarkSetting
import java.io.File


class PublishActivity : BaseActivity(),PLRecordStateListener {
    private lateinit var binding:ActivityPublishBinding
    private lateinit var mShortVideoRecorder:PLShortVideoRecorder
    override fun releaseRes() {
    }

    override fun generateContentView(): View {
        binding=ActivityPublishBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        mShortVideoRecorder = PLShortVideoRecorder()
        mShortVideoRecorder.setRecordStateListener(this)
        configPLParams()
    }

    private fun configPLParams() {
        // 摄像头采集选项
        val cameraSetting = PLCameraSetting()
        cameraSetting.setCameraId(PLCameraSetting.CAMERA_FACING_ID.CAMERA_FACING_FRONT)
        cameraSetting.setCameraPreviewSizeRatio(PLCameraSetting.CAMERA_PREVIEW_SIZE_RATIO.RATIO_4_3)
        cameraSetting.setCameraPreviewSizeLevel(PLCameraSetting.CAMERA_PREVIEW_SIZE_LEVEL.PREVIEW_SIZE_LEVEL_480P)
        // 麦克风采集选项
        val microphoneSetting = PLMicrophoneSetting()
        // 视频编码选项
        val videoEncodeSetting = PLVideoEncodeSetting(this)
        videoEncodeSetting.setEncodingSizeLevel(PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_1) // 480x480

        videoEncodeSetting.setEncodingBitrate(1000 * 1024) // 1000kbps

        videoEncodeSetting.setEncodingFps(25)
        videoEncodeSetting.setHWCodecEnabled(true) // true:硬编 false:软编

        //MediaCodec - 硬编 FFmpeg - 软编
        // 音频编码选项
        val audioEncodeSetting = PLAudioEncodeSetting()
        audioEncodeSetting.setHWCodecEnabled(true) // true:硬编 false:软编

        // 美颜选项
        val faceBeautySetting = PLFaceBeautySetting(1.0f, 0.5f, 0.5f)
        // 录制选项
        val recordSetting = PLRecordSetting()
        recordSetting.setMaxRecordDuration((10 * 1000).toLong()) // 10s

        val path = Environment.getExternalStorageDirectory().absolutePath
        recordSetting.setVideoCacheDir(path)
        recordSetting.setVideoFilepath(path+File.separator+ConstantValue.RECODE_VIDEO_FILENAME)
        // 设置录制速度 (默认为 1.0)
//        mShortVideoRecorder.setRecordSpeed(1.0)



        mShortVideoRecorder.prepare(binding.glsvPublish, cameraSetting, microphoneSetting,
            videoEncodeSetting, audioEncodeSetting, faceBeautySetting, recordSetting);

        addWaterMarker()
    }

    /**
     * 添加水印
     */
    private fun addWaterMarker() {
        val mWatermarkSetting = PLWatermarkSetting()
        mWatermarkSetting.resourceId = R.mipmap.sym_def_app_icon
        mWatermarkSetting.setPosition(0.01f, 0.75f)
        mWatermarkSetting.alpha = 128
        mShortVideoRecorder.setWatermark(mWatermarkSetting)
    }

    override fun initData() {
    }

    //正在录制
    private var isRecoding = false
    override fun initEvent() {
        binding.btnPublishRecode.setOnClickListener {
            val filters =  mShortVideoRecorder.builtinFilterList
            if (filters!=null&&filters.size>0){
                filters.forEach {
                    LogUtils.d("filters","filterName = ${it.name}")
                }
                mShortVideoRecorder.setBuiltinFilter(filters.get(2).name)
            }
//            mShortVideoRecorder.setBuiltinFilter("candy")
            if (isRecoding){
                mShortVideoRecorder.endSection()
                mShortVideoRecorder.concatSections(object :PLVideoSaveListener{
                    override fun onSaveVideoSuccess(p0: String?) {
//                        shortVideoEditor.stopPlayback()
//                        mShortVideoRecorder.destroy()
                        showMsg("录制成功")

                    }

                    override fun onSaveVideoFailed(p0: Int) {
                        showMsg("录制失败，errCode:${p0}")
                    }

                    override fun onSaveVideoCanceled() {
                        showMsg("取消录制")
                    }

                    override fun onProgressUpdate(p0: Float) {

                    }

                })
                binding.btnPublishRecode.text = "Start"
            }else{
                mShortVideoRecorder.beginSection()
                binding.btnPublishRecode.text="Stop"
            }

            isRecoding=!isRecoding
        }

        binding.btnPublisEdit.setOnClickListener {
            val videoPath = Environment.getExternalStorageDirectory().absolutePath+ File.separator+ConstantValue.RECODE_VIDEO_FILENAME
            val dstPath = Environment.getExternalStorageDirectory().absolutePath+ File.separator+ConstantValue.RECODE_VIDEO_DST_FILENAME
            val file = File(videoPath)
            if (!file.exists()){
                showMsg("要剪辑的视频文本不存在，快去录制吧")
                return@setOnClickListener
            }
            initEditSetting(videoPath,dstPath,true)
            addFilter()
        }
    }

    /**
     * 添加滤镜
     */
    private fun addFilter() {
        if (::shortVideoEditor.isInitialized){
            val filterList =  shortVideoEditor.builtinFilterList
            if (filterList!=null&&filterList.size>0){
                shortVideoEditor.setBuiltinFilter(filterList.get(0).name)
            }

//            shortVideoEditor.startPlayback()
        }
    }

    private lateinit var shortVideoEditor: PLShortVideoEditor

    private fun initEditSetting(src:String,dst:String,isKeep:Boolean){
        val setting = PLVideoEditSetting()
        // 视频源文件路径
        setting.setSourceFilepath(src)
        // 编辑后保存的目标文件路径
        setting.setDestFilepath(dst)
        // 编辑保存后，是否保留源文件
        setting.setKeepOriginFile(isKeep)

        shortVideoEditor=PLShortVideoEditor(binding.glsvPublish,setting)
    }

    override fun onReady() {

    }

    override fun onError(p0: Int) {

    }

    override fun onDurationTooShort() {

    }

    override fun onRecordStarted() {

    }

    override fun onSectionRecording(p0: Long, p1: Long, p2: Int) {

    }

    override fun onRecordStopped() {

    }

    override fun onSectionIncreased(p0: Long, p1: Long, p2: Int) {

    }

    override fun onSectionDecreased(p0: Long, p1: Long, p2: Int) {

    }

    override fun onRecordCompleted() {

    }

    override fun onResume() {
        super.onResume()
        mShortVideoRecorder.resume()
    }

    override fun onPause() {
        super.onPause()
        mShortVideoRecorder.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mShortVideoRecorder.destroy()
    }
}